package leetcode.f1t100;

import leetcode.struct.ListNode;

/**
 * 合并两个有序链表
 * https://leetcode.com/problems/merge-two-sorted-lists/
 *
 * @Author lichongxiao
 * @Date 2022/9/30 10:24
 */
public class Q21_MergeTwoSortedList {
    public static void main(String[] args) {
        new Q21_MergeTwoSortedList().test();
    }
    private void test(){
        ListNode list1 = new ListNode(1,new ListNode(2,new ListNode(4,null)));
        ListNode list2 = new ListNode(1,new ListNode(3,new ListNode(4,null)));
        ListNode head = mergeTwoLists(list1,list2);
        while(head!=null){
            System.out.println(head.val);
            head = head.next;
        }
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = new ListNode();
        ListNode cur = head;
        while(list1 != null && list2 != null){
            if(list1.val <= list2.val){
                cur.next = list1;
                list1 = list1.next;
            }else{
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        if(list1 != null) {
            cur.next = list1;
        }else{
            cur.next = list2;
        }
        return head.next;
    }
}
